package com.robooot.business_counter.service;

import com.robooot.business_counter.dao.DeviceDao;
import com.robooot.business_counter.dao.UserDao;
import com.robooot.business_counter.entity.UserInfo;
import com.robooot.business_counter.model.RemoteUrl;
import com.robooot.business_counter.model.Token;
import com.robooot.business_counter.model.UserVo;
import com.robooot.business_counter.util.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.ref.PhantomReference;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private DeviceDao deviceDao;
    @Autowired
    private RemoteUrl remoteUrl;
    @Autowired
    private RemoteService remoteService;

    private final Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 给用户闪易app推送消息
     * @param userVo
     */
    public void forwardNews(UserVo userVo) {
        String userId = userDao.getUserId(userVo.getPhone());
        String deviceName = deviceDao.getDeviceName(userVo.getDeviceId());
        Map params = new HashMap();
        params.put("userId", userId);
        params.put("bizType", "Express");
        params.put("title", "邮政快递");
        params.put("content","您的快递已经帮你放到"+deviceName+"柜门号"+ userVo.getCounterNumber());
        remoteService.callWithSign(remoteUrl.getCreateNormal(), params);
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    public UserInfo getUserInfo(String userId) {
        UserInfo userInfo = new UserInfo();
        Map user = getUserPhoneByRemote(userId);
        userInfo.setUserPhone((String) user.get("name"));
        userInfo.setUserName((String) user.get("nickName"));
        userInfo.setUserId(userId);
        return userInfo;
    }

    private Map getUserPhoneByRemote(String userId) {
        Map params = new HashMap();
        params.put("userId", userId);
        Map user = remoteService.callWithSign(remoteUrl.getGetBaseUser(), params);
        String phone = (String) user.get("name");
        return user;
    }

    public String getUserId(String token) {
        Map params = new HashMap();
        params.put("token", token);
        Map map = remoteService.callWithSign(remoteUrl.getToken(), params);
        Token tokenUser = JsonUtil.object2Bean(map, Token.class);
        return tokenUser.getUserId();
    }

    public UserVo getUser(String userPhone) {
        return userDao.getUser(userPhone);
    }
}
